use Purple;
use HTTP::Request;
use XML::XPath;
use XML::XPath::XMLParser;

%PLUGIN_INFO = (
    perl_api_version => 2,
    name => "Twitter Status",
    version => "0.2.3",
    summary => "Use a Twitter feed as your status message.",
    description => "Use a Twitter feed as your status message.",
    author => "Aaron D. Santos aaronds109\@gmail.com, Kurt Nelson kurt\@thisisnotajoke.com and Patrick Tulskie patricktulskie\@gmail.com",
    url => "http://code.google.com/p/pidgin-twitterstatus/",

    load => "plugin_load",
    unload => "plugin_unload",    
    prefs_info => "prefs_info_cb"
);

#Begin Global Variables
#If you want to have a font and color then put stuff in the quotes here.  Otherwise just leave the quotes empty.
my $styleStart = "";
my $styleEnd = "";
#End Global Variables

sub fetch_url_cb
{
	my $response = shift;
	
	my $xml = XML::XPath->new(xml=>$response);
	my @statuses = $xml->find('/statuses/status')->get_nodelist();
	$status_message = @statuses[0]->find('text')->string_value;
	Purple::Debug::info("Twitter Status Feed", "Status Message: " . $status_message . "\n");
	
	
	my $saved_status = Purple::SavedStatus::get_current();
	my $statusType = $saved_status->get_type();
	my $prev_status = $saved_status->get_message();
	Purple::Debug::info("Twitter Status Feed","Your status type is ".$statusType. "\n");
	if(!($keepOnAway && $statusType == 6))
	{
		if(($prev_status ne $status_message) && (length($status_message) > 1) && (index($status_message, '@') != 0))
		{
			Purple::Debug::info("Twitter Status Feed", "Updating status message with ".$status_message." From ".$twitterurl."\n");
			$saved_status->set_message($styleStart . $status_message . $styleEnd);
			$saved_status->set_type($statusType);
			$saved_status->activate();
		}else{
		      Purple::Debug::info("Twitter Status Feed","Not updating status because it has not changed, was too short, or started with an @\n");
		}
	}else{
		Purple::Debug::info("Twitter Status Feed","Not updating status because you are away and like your message\n");
	}
}

sub timeout_cb
{
	Purple::Debug::info("Twitter Status Feed", "Starting the sequence.  Pidgin's timer expired.\n");
	my $plugin = shift;
	
	my $twitterusername = Purple::Prefs::get_string("/plugins/core/gtk-aaron_ds-twitterstatus/twitterusername");
	my $twitterurl = "http://twitter.com/statuses/user_timeline/".$twitterusername.".xml?count=1";
	#if the timeout cannot be parsed, 0 will result
	my $timeout = 0+Purple::Prefs::get_string("/plugins/core/gtk-aaron_ds-twitterstatus/timeout");
	my $keepOnAway = Purple::Prefs::get_bool("/plugins/core/gtk-aaron_ds-twitterstatus/onaway");
	my $status_message = "";
	if($twitterusername eq ""){
	 Purple::Debug::info("Twitter Status Feed","Blank username\n");
	 die "blank username";
	}
	my $agent = "pidgin-twitterstatusfeed/1.0";
	
	#give some timeout if not otherwise specified
	if($timeout eq 0)
	{
		Purple::Debug::info("Twitter Status Feed", "Could not parse timeout field. Using 20 seconds default.\n");
		$timeout = 20
	}
	
	Purple::Debug::info("Twitter Status Feed", "Fetching URL.\n");
	Purple::Util::fetch_url($plugin, $twitterurl, TRUE, $agent,TRUE, "fetch_url_cb");		
		
	# Reschedule timeout
	Purple::Debug::info("Twitter Status Feed", "Rescheduling timer.\n");
	Purple::timeout_add($plugin, $timeout, \&timeout_cb, $plugin);
	Purple::Debug::info("Twitter Status Feed", "New timer set for " . $timeout . " seconds.\n");

}



sub plugin_init
{
    return %PLUGIN_INFO;
}

sub plugin_load
{
    my $plugin = shift;
    Purple::Debug::info("Twitter Status Feed", "plugin_load() - Twitter Status Feed.\n");
    
    # Here we are adding a set of preferences
    #  The second argument is the default value for the preference.
    Purple::Prefs::add_none("/plugins/core/gtk-aaron_ds-twitterstatus");
    Purple::Prefs::add_string("/plugins/core/gtk-aaron_ds-twitterstatus/twitterusername", "");
    Purple::Prefs::add_bool("/plugins/core/gtk-aaron_ds-twitterstatus/onidleonly", "");
    Purple::Prefs::add_bool("/plugins/core/gtk-aaron_ds-twitterstatus/onaway","");
	Purple::Prefs::add_string("/plugins/core/gtk-aaron_ds-twitterstatus/timeout", "120");
    
     # Schedule a timeout for 1 second from now
    Purple::timeout_add($plugin, 10, \&timeout_cb, $plugin);
}

sub plugin_unload
{
    my $plugin = shift;
    Purple::Debug::info("Twitter Status Feed", "plugin_unload() - Twitter Status Feed.\n");
}

sub prefs_info_cb
{
    # The first step is to initialize the Purple::Pref::Frame that will be returned
    $frame = Purple::PluginPref::Frame->new();

    # Create a new boolean option with a label "Boolean Label" and then add
    # it to the frame
    $ppref = Purple::PluginPref->new_with_label("Twitter Account Information");
    $frame->add($ppref);

    # Create a text box.  The default value will be "Foobar" as set by
    # plugin_load
    $ppref = Purple::PluginPref->new_with_name_and_label(
        "/plugins/core/gtk-aaron_ds-twitterstatus/twitterusername", "Twitter User Name");
    $ppref->set_type(2);
    $ppref->set_max_length(120);
    $frame->add($ppref);
	
	#Adding the timeout box
	$tpref = Purple::PluginPref->new_with_name_and_label("/plugins/core/gtk-aaron_ds-twitterstatus/timeout", "Timeout Period");
	#TODO: look to see if this type can be automatically set to be an integer so we don't need to parse it later
    $tpref->set_type(2);
    $tpref->set_max_length(3);
    $frame->add($tpref);

	#Update on Away
    $ppref = Purple::PluginPref->new_with_name_and_label(
    	   "/plugins/core/gtk-aaron_ds-twitterstatus/onaway", "Preserve Pidgin status when extended away");
    $ppref -> set_type(3);
    $frame->add($ppref);

    return $frame;
}
